import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Cart from '../views/Cart.vue'
import Category from '../views/Category.vue'
import Topic from '../views/Topic.vue'
import User from '../views/User.vue'
import ProductsDetail from '../views/ProductsDetail.vue'

// 高版本router会有一个错误，当重复点击同一个路由时时会报错
// 解决方法：1，降级 cnpm i vue-router@3.0.7    2,每个push方法后面带.catch(err=>)
// 3，直接修改原型方法push
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
    return originalPush.call(this, location).catch(err => {})
}

// 必须写在VueRouter注册之前
Vue.use(VueRouter)

const routes = [{
        path: '/',
        redirect: '/home', //路由重定向
    },
    {
        path: '/home',
        name: 'Home',
        component: Home,
        meta: {
            activeNum: 0,
            isShowTabber: true
        },
        children: [{
            path: '/home/searchPopup',
            name: 'SearchPopup',
            component: () =>
                import ('../views/SearchPopup.vue'),
        }]
    },
    {
        path: '/cart',
        name: 'Cart',
        component: Cart,
        meta: {
            activeNum: 3,
            isShowTabber: true
        },
    },
    {
        path: '/category',
        name: 'Category',
        component: Category,
        meta: {
            activeNum: 2,
            isShowTabber: true
        },
    },
    {
        path: '/topic',
        name: 'Topic',
        component: Topic,
        meta: {
            activeNum: 1,
            isShowTabber: true
        },
    },
    {
        path: '/user',
        name: 'User',
        component: User,
        meta: {
            activeNum: 4,
            isShowTabber: true
        },
    },
    {
        path: '/productsDetail',
        name: 'ProductsDetail',
        component: ProductsDetail,
    },

]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

/**
 * 路由拦截器，当跳转其他路由时，判断是否有token，反则回到登录页
 */
router.beforeEach((to, from, next) => {
    console.log(to)
    if (to.path == '/cart') {
        let token = localStorage.getItem("token")
        if (token) {
            next()
        } else {
            Vue.prototype.$toast("请先登录~")
            setTimeout(() => {
                router.push("/user")
            }, 1000)

        }
    } else {
        next()

    }



})





export default router